/**
 * @description  指数监控
 * @author swl
 */
import React, { PropTypes, PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Tabs, message, Switch } from 'antd';
import { ContentPackage, DATA_ENTRY, AdvancedSearch, PrimaryGhostC, NoQueryC } from '../../../comps';
import uuid from 'es6-uuid';
import delPng from '../../../assets/frame/clear.png';
import TargetTable from './targetTable';
import styles from './index.less';
import ReactDOM from 'react-dom';
import { values } from 'regenerator-runtime';

const { TabPane } = Tabs;
@Form.create()
class IndexMonitoring extends PureComponent {
  state = {
    indexArr: [], //指数名称
    tabPage: [], //tab页显示
    activeKey: undefined,
    indexCode: '',
    indexName: '',
    heightOrigin: undefined, //当前组件top值,确定区间收益率按钮位置
  };

  componentDidMount() {
    this.windowChange();
    const { dispatch } = this.props;
    //默认加载沪深300数据
    dispatch({
      type: 'indexMonitoringM/queryByCode',
      payload: {
        value: '沪深300',
      },
      callback: (res) => {
        let arr =
          res.dataSource &&
          res.dataSource.map((item) => {
            return { value: item.id, title: item.value + '-' + item.title };
          });
        if (arr.length > 0) {
          this.setState(
            {
              indexArr: arr,
              indexCode: arr[0].value,
              indexName: arr[0].title,
            },
            () => {
              this.changeTabs({ indexCode: arr[0].value });
            },
          );
        }
      },
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.nowKey == true && this.timer == 'clear') {
      if (this.state.activeKey) {
        this.timer = setInterval(() => {}, 10000);
        let key = 'TargetTable' + this.state.activeKey;
        this.state[key].refresh();
      }
    } else if (nextProps.nowKey == false) {
      //离开前清除掉定时器
      this.timer && clearInterval(this.timer);
      this.timer = 'clear';
      //tab页隐藏时，取消定时刷新
      this.state.tabPage.map((item, index) => {
        let refName = 'TargetTable' + (index + 1);
        this.state[refName].clearTime();
      });
    }
  }

  componentWillUnmount() {
    //离开前清除掉定时器
    this.timer && clearInterval(this.timer);
    this.timer = null;
    //tab页隐藏时，取消定时刷新
    this.state.tabPage.map((item, index) => {
      let refName = 'TargetTable' + (index + 1);
      this.state[refName].clearTime();
    });
  }

  // 窗口大小变更触发
  windowChange = () => {
    setTimeout(() => {
      try {
        //获取组件当前位置,确定区间收益率按钮位置
        const domTop = ReactDOM.findDOMNode(this).getBoundingClientRect();
        this.setState({
          heightOrigin: domTop.top,
        });
      } catch (err) {
        this.setState({
          heightOrigin: 50,
        });
      }
    }, 0);
  };

  //指数名称切换
  indexCodeChange = (e) => {
    let ds = this.state.indexArr.filter((item) => {
      return item.value === e;
    });
    this.setState({
      indexName: ds.length > 0 ? ds[0].title : '',
    });
  };

  //指数名称搜索
  indexCodeSearch = (e) => {
    if (e) {
      this.timer ? clearTimeout(this.timer) : '';
      this.timer = setTimeout(() => {
        this.props.dispatch({
          type: 'indexMonitoringM/queryByCode',
          payload: {
            value: e,
          },
          callback: (res) => {
            let arr =
              res.dataSource &&
              res.dataSource.map((item) => {
                return { value: item.id, title: item.value + '-' + item.title };
              });
            this.setState({
              indexArr: arr,
            });
          },
        });
      });
    }
  };

  // 工具栏渲染
  renderToolbar() {
    const { indexArr, indexCode } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'indexCode',
          title: '指数名称',
          type: DATA_ENTRY.SELECT,
          initialValue: indexCode,
          dataSource: indexArr,
          allowClear: true,
          filterOption: false,
          onChange: (e) => this.indexCodeChange(e),
          onSearch: (e) => this.indexCodeSearch(e),
        },
        {
          dataIndex: 'industry',
          title: '所属行业',
          type: DATA_ENTRY.INDUSTRYC,
          multiple: true,
          isUnfold: false,
        },
      ],
      selfButt: (
        <PrimaryGhostC
          title='刷新'
          onClick={() => {
            let values = this.advancedSearch.props.form.getFieldsValue();
            if (values.indexCode) {
              if (this.state.activeKey) {
                let key = 'TargetTable' + this.state.activeKey;
                this.state[key].refresh();
              }
            } else {
              message.info('未匹配，请输入查询条件。');
            }
          }}
          style={{ marginLeft: '16px' }}
        />
      ),
      onQuery: (e) => {
        //tab页隐藏时，取消定时刷新
        this.state.tabPage.map((item, index) => {
          let refName = 'TargetTable' + (index + 1);
          this.state[refName].clearTime();
        });
        this.changeTabs(e);
      },
      onClear: () => {
        this.setState({
          indexCode: '',
          indexName: '',
        });
        this.props.form.resetFields();
      },
      onRef: (ref) => {
        this.advancedSearch = ref;
      },
    };

    return <AdvancedSearch {...searchProps} />;
  }

  // tab切换时调用
  handleChangeTab = (value) => {
    if (value == 'deleteAll') {
      let index = parseInt(this.state.activeKey);
      let arr = this.state.tabPage.slice(index - 1, index);
      this.setState(
        {
          tabPage: arr,
          activeKey: '1',
        },
        () => {
          this.setSearch(1);
        },
      );
    } else {
      this.setSearch(value);
      this.setState({
        activeKey: value,
      });
    }
  };

  //查询时tab修改
  changeTabs = (e) => {
    const { tabPage, activeKey, indexName, indexArr } = this.state;
    let arr = [...tabPage];
    let obj = {
      indexCode: e.indexCode,
      industry: e.industry,
      name: indexName,
      indexArr: indexArr,
    };
    let pageCurrent;
    //判断tab页是否已经存在指数名称，若存在值修改tab页e
    let hasTab = false;
    // 当前tab页已经存在指数名称，查询条件是否变化
    let haschange = false;
    if (e.indexCode) {
      arr.map((item, index) => {
        if (e.indexCode == item.indexCode) {
          haschange = item.industry != e.industry;
          item.industry = obj.industry;
          hasTab = true;
          pageCurrent = index + 1;
        }
      });
      if (!hasTab) arr.push(obj);
    } else {
      message.warning(`请选择指数名称`);
    }
    this.setState(
      {
        tabPage: arr,
        activeKey: pageCurrent ? pageCurrent.toString() : arr.length.toString(),
      },
      () => {
        // 点击查询时，判断是否要刷新（tab页已存在并且查询条件未改变时调用，查询条件改变时组件内会刷新）
        if (activeKey && hasTab && !haschange) {
          let key = 'TargetTable' + activeKey;
          this.state[key].refresh();
        }
      },
    );
  };

  //tab切换时，修改顶部搜索内容
  setSearch = (key) => {
    if (this.state.tabPage.length > 0) {
      let obj = this.state.tabPage[key - 1];
      this.setState({
        indexArr: obj.indexArr,
      });
      this.advancedSearch.props.form.setFieldsValue({
        indexCode: obj.indexCode,
        industry: obj.industry,
      });
      //tab页隐藏时，取消定时刷新
      this.state.tabPage.map((item, index) => {
        let refName = 'TargetTable' + (index + 1);
        if (key != index + 1) {
          this.state[refName].clearTime();
        } else {
          this.state[refName].refresh();
        }
      });
    } else {
      this.advancedSearch.props.form.setFieldsValue({
        indexCode: undefined,
        industry: undefined,
      });
    }
  };

  //tabs关闭事件
  onEdit = (targetKey, action) => {
    this[action](targetKey);
  };

  remove = (targetKey) => {
    let arr = [...this.state.tabPage];
    arr.splice(targetKey - 1, 1);
    this.setState(
      {
        tabPage: arr,
        activeKey: '1',
      },
      () => {
        this.setSearch(1);
      },
    );
  };

  render() {
    const { activeKey, tabPage, heightOrigin } = this.state;
    return (
      <ContentPackage
        title='指数监控'
        contentHtml={
          <div className={styles.indexMonitoring}>
            {this.renderToolbar()}
            <div style={{ position: 'relative' }}>
              {tabPage && tabPage.length ? (
                <>
                  <Tabs hideAdd activeKey={activeKey} onChange={this.handleChangeTab} onEdit={this.onEdit} type='editable-card' style={{ paddingTop: '20px' }}>
                    {tabPage.map((item, index) => {
                      let refName = 'TargetTable' + (index + 1);
                      return (
                        <TabPane closable={true} tab={item.name} key={index + 1}>
                          <TargetTable
                            key={item.name}
                            onRef={(ref) => this.setState({ [refName]: ref })}
                            activeKey={activeKey}
                            indexKey={index + 1}
                            heightOrigin={heightOrigin}
                            assetTypes={item.assetTypes}
                            indexCode={item.indexCode}
                            industry={item.industry}
                          />
                        </TabPane>
                      );
                    })}
                    <TabPane closable={false} tab={<img src={delPng} />} key={'deleteAll'}></TabPane>
                  </Tabs>
                </>
              ) : (
                <div style={{ marginTop: '10px' }}>
                  <NoQueryC />
                </div>
              )}
            </div>
          </div>
        }
      />
    );
  }
}
export default connect(({ loading }) => ({ loading }))(IndexMonitoring);
